package ace.cmp.id.generator.uuid.core;

import ace.cmp.id.generator.api.StringIdGenerator;
import ace.cmp.id.generator.uuid.core.generator.UUIDRandomIdGenerator;
import ace.cmp.id.generator.uuid.core.generator.UUIDRandomIdGeneratorImpl;
import ace.cmp.id.generator.uuid.core.generator.UUIDTimeBaseIdGenerator;
import ace.cmp.id.generator.uuid.core.generator.UUIDTimeBaseIdGeneratorImpl;
import ace.cmp.id.generator.uuid.core.property.UUIDProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * @author Caspar auto config uuid sequence
 */
@ConditionalOnProperty(
    value = "ace.cmp.id.generator.uuid.enable",
    matchIfMissing = true,
    havingValue = "true")
@EnableConfigurationProperties({UUIDProperties.class})
@Configuration
public class UUIDIdGeneratorBootstrapAutoConfig {

  @Bean
  @ConditionalOnMissingBean
  public UUIDTimeBaseIdGenerator uuidTimeBaseIdGenerator() {
    return new UUIDTimeBaseIdGeneratorImpl();
  }

  @Bean
  @ConditionalOnMissingBean
  public UUIDRandomIdGenerator uuidRandomIdGenerator() {
    return new UUIDRandomIdGeneratorImpl();
  }

  @Primary
  @Bean
  public StringIdGenerator uuidIdGenerator(
      UUIDProperties properties,
      UUIDTimeBaseIdGenerator uuidTimeBaseIdGenerator,
      UUIDRandomIdGenerator uuidRandomIdGenerator) {
    if (UUIDProperties.UUIDVersionEnum.UUID_V1_TIME_BASE.equals(properties.getDefaultType())) {
      return uuidTimeBaseIdGenerator;
    }
    return uuidRandomIdGenerator;
  }
}
